// 实现这个项目的构建任务

const { src, dest, series, parallel, watch } = require("gulp");
const del = require("del");
const browserSync = require("browser-sync");
const bs = browserSync.create();
/**
 * gulp-sass
 * gulp-babel
 * gulp-swig
 * gulp-imagemin
 * gulp-load-plugins
 *
 * gulp-htmlmin
 * gulp-uglify
 * gulp-clean-css
 * gulp-if
 *
 * del
 * browser-sync
 */
const plugins = require("gulp-load-plugins")();

const clean = () => {
  return del(["dist", "temp"]);
};

const data = {
  pkg: {
    name: "wlz",
    description: "wlz-gulp-sample",
    homepage: "首页",
    author: {
      url: "https://gitee.com/xiaoxiaozhi007/large_front_end_of_retractor",
    },
  },
};

const style = () => {
  return src("src/assets/styles/*.scss", { base: "src" })
    .pipe(plugins.sass({ outputStyle: "expanded" }))
    .pipe(dest("temp"));
};

const script = () => {
  return src("src/assets/scripts/*.js", { base: "src" })
    .pipe(plugins.babel({ presets: ["@babel/preset-env"] }))
    .pipe(dest("temp"));
};

const page = () => {
  return src("src/*.html", { base: "src" })
    .pipe(plugins.swig({ data, defaults: { cache: false } }))
    .pipe(dest("temp"));
};

const image = () => {
  return src("src/assets/images/*", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

const font = () => {
  return src("src/assets/fonts/*", { base: "src" })
    .pipe(plugins.imagemin())
    .pipe(dest("dist"));
};

const other = () => {
  return src("public/**").pipe(dest("dist"));
};

const server = () => {
  watch("src/assets/styles/*.js", style);
  watch("src/assets/scripts/*.js", script);
  watch("src/*.html", page);
  watch(["public/**", "src/assets/fonts/*", "src/assets/images/*"], bs.reload);

  bs.init({
    notify: false,
    port: 8089,
    files: "temp/**",
    server: {
      baseDir: ["temp", "src", "public"],
      routes: {
        "/node_modules": "node_modules",
      },
    },
  });
};

/**
 * gulp-useref 资源合并
 *
 * gulp-htmlmin 压缩html
 * gulp-uglify 压缩js
 * gulp-clean-css 压缩css
 *
 * gulp-if 判断文件类型
 */

const compress = () => {
  return src("temp/*.html", { base: "temp" })
    .pipe(plugins.useref({ searchPath: ["temp", "."] }))
    .pipe(plugins.if(/\.js$/, plugins.uglify()))
    .pipe(plugins.if(/\.css$/, plugins.cleanCss()))
    .pipe(
      plugins.if(
        /\.html$/,
        plugins.htmlmin({
          collapseWhitespace: true,
          minifyCSS: true,
          minifyJS: true,
        })
      )
    )
    .pipe(dest("dist"));
};

const compile = parallel(style, script, page);
const develop = series(compile, server);

const build = series(
  clean,
  parallel(series(compile, compress), font, image, other)
);

module.exports = {
  clean,
  develop,
  build,
};
